#!/bin/bash


ACTION=$1
ID=${2-""}
SERVER=10.10.10.10:16104
S=100000
T=5000000
R=10000000
VERBOSE=1

if [ "$ACTION" == "MONITOR" ] ;then # monitor the distribution of calls to the agents.
    while ((1)); do 
        find logs.agent.id.* -maxdepth 0 | xargs -i echo "echo -n \"test {} \" ; find {} |wc -l" |sh;  
        sleep 1; 
        date; 
    done
elif [ "$ACTION" == "STAT" ] ;then
    echo "/REQUEST status:"
    mqttsample_array -s $SERVER -n 1 -q 0 -t /REQUEST -a subscribe -x unsubscribe=0 -x retainedMsgCounted=1 -v -v | grep "received on"
    echo "/REPLY status:"
    mqttsample_array -s $SERVER -n 1 -q 0 -t /REPLY   -a subscribe -x unsubscribe=0 -x retainedMsgCounted=1 -v -v | grep "received on"
    echo "/CONFIRM status:"
    mqttsample_array -s $SERVER -n 1 -q 0 -t /CONFIRM -a subscribe -x unsubscribe=0 -x retainedMsgCounted=1 -v -v | grep "received on"
    
elif [ "$ACTION" == "SERVER" ] ;then
    rm -rf logs.SERVER
    mkdir logs.SERVER
    #----------------------------
    # to make things easy for now, if you restart the server it clears out all the old state
    # Additional Exercise: make server recover and continue with old state.
    #----------------------------
    if (($VERBOSE>0)); then 
        echo -n "1" # STATUS
    fi
    mqttsample_array -s $SERVER -n 1 -q 0 -t /REQUEST -a publish -x unsubscribe=0 -i agent.server.1 -c false -v -v -x msgFile=NULLMSG -x retainedFlag=1 > /dev/null

id=1;
while((1)); do
    rm -rf logs.server/log.messageid.$id
    mkdir -p logs.server/log.messageid.$id
    echo ""
    echo "`date` `date +%s.%N` Start working on customer id: $id"
    #----------------------------
    # At the start of processing each customer request /CONFIRM and /REPLY should always be empty
    #----------------------------
    if (($VERBOSE>0)); then 
        echo -n "2" # STATUS
    fi
    mqttsample_array -s $SERVER -n 1 -q 0 -t /CONFIRM -a publish -x unsubscribe=0 -i agent.server.1 -c false -v -v -x msgFile=NULLMSG -x retainedFlag=1 > /dev/null
    if (($VERBOSE>0)); then 
        echo -n "3" # STATUS
    fi
    mqttsample_array -s $SERVER -n 1 -q 0 -t /REPLY -a publish -x unsubscribe=0 -i agent.server.1 -c false -v -v -x msgFile=NULLMSG -x retainedFlag=1 > /dev/null
    if (($VERBOSE>0)); then 
        echo -n "4" # STATUS
    fi
    subid=1;
    msgflowcomplete=0 
    while((1)); do
        msg=" Message_id: $id subid: $subid `date` "
        data=`mqttsample_array -s $SERVER -n 1 -q 0 -t /REQUEST -a publish -x unsubscribe=0 -i agent.server.1 -c false -v -v -m "$msg" -x retainedFlag=1 2>&1 | tee -a log.SERVER.pub`
        if (($VERBOSE>1)); then 
            echo "-----------------------------------"
            echo "step 1 : $data"
            echo "-----------------------------------"
        elif (($VERBOSE>0)); then 
            echo -n "p" # STATUS
        fi

        replystart=`date +%s%N`
        while((1)); do
            curtime=`date +%s%N`
            let deltatime=($curtime-$replystart)
            if (($deltatime>$T)); then
                if (($VERBOSE>0)); then 
                    echo -n "z" # STATUS
                fi
                break; # retry republish same message
            fi
            if (($VERBOSE>0)); then 
                echo -n "S"
            fi
            data=`mqttsample_array -s $SERVER -n 1 -q 0 -t /REPLY -a subscribe -x unsubscribe=0 -x retainedMsgCounted=1 -x msgTimeoutAfterSub=$T -i agent.server.1 -c false -v -v 2>&1 | tee -a log.SERVER.reply`
            if (($VERBOSE>1)); then 
                echo "-----------------------------------"
                echo "step 2: $data"
                echo "-----------------------------------"
            elif (($VERBOSE>0)); then 
                echo -n "s"
            fi
            replyid=`echo "$data" | grep -oE ' Message_id: .*' | awk '{print $2}'`
            replysubid=`echo "$data" | grep -oE ' subid: .*' | awk '{print $2}'`
            #echo "reply id is: $replyid"
            #echo "data is : "
            #echo "$data" | grep "received on"
            if [ "$replyid" == "$id" ] ;then
                echo -n "R" ; # wait for confirmation
                confirmstart=`date +%s%N`
                while((1)); do
                    curtime=`date +%s%N`
                    let deltatime=($curtime-$confirmstart)
                    if (($deltatime>$T)); then
                        if (($VERBOSE>0)); then 
                            echo -n "y" # STATUS
                        fi
                        break; # retry republish same message
                    fi
                    data=`mqttsample_array -s $SERVER -n 1 -q 0 -t /CONFIRM -a subscribe -x unsubscribe=0 -x retainedMsgCounted=1 -x msgTimeoutAfterSub=$R -v -v 2>&1 | tee -a log.SERVER.confirm`
                    if (($VERBOSE>1)); then 
                        echo "-----------------------------------"
                        echo "step 3: $data"
                        echo "-----------------------------------"
                    fi
                    confid=`echo "$data" | grep -oE ' Message_id: .*' | awk '{print $2}'`
                    confsubid=`echo "$data" | grep -oE ' subid: .*' | awk '{print $2}'`
                    if [ "$confid" == "$id" ] ;then
                        echo -n "U" # STATUS
                        msgflowcomplete=1 
                        break;
                    else 
                        echo -n "u" # STATUS
                    fi
                done
                if [ "$msgflowcomplete" == "1" ] ;then
                    echo -n "C" # STATUS
                    break;
                fi
            else
                #echo -n "r $replyid != $id" ; # STATUS received a reply on an id that we are not concerned about.
                echo -n "r"
            fi

    done
    if [ "$msgflowcomplete" == "1" ] ;then
        echo -n "D" # STATUS
        break;
    fi
 
  let subid=$subid+1 ; #process next customer in queue
  done
  #exit 1;
  mv log.SERVER.* logs.server/log.messageid.$id
  rm -rf log.SERVER.*
  let id=$id+1 ; #process next customer in queue
done

elif [ "$ACTION" == "AGENT" ] ;then

if [ -z "$ID" ] ;then
    echo "ERROR: must specify a unique id number for agent to use"
    exit 1;
fi

rm -rf logs.agent.id.$ID
mkdir logs.agent.id.$ID

while((1)); do
data=`mqttsample_array -s $SERVER -n 1 -q 0 -t /REQUEST -a subscribe -x unsubscribe=0 -x retainedMsgCounted=1 -x sharedSubscription=AGENTQ -i agent.client.$ID -c false -x msgTimeoutAfterSub=$S -v -v 2>&1 | tee -a log.agent.$ID.request`

replyid=`echo "$data" | grep -oE ' Message_id: .*' | awk '{print $2}'`
if [ -z "$replyid" ] ;then
    echo "Got no message "
    continue;
fi

echo "$data"
mesg="REPLY TO: "
mesg+=`echo "$data" | grep "received on" | grep -oE ' m: .*' `

echo ============================================================
echo ============================================================
echo ============================================================
echo ============================================================
echo ============================================================
echo ============================================================
echo "msg is \"$mesg\""
echo ============================================================
echo ============================================================
echo ============================================================
echo ============================================================
echo ============================================================


data=`mqttsample_array -s $SERVER -n 1 -q 0 -t /REPLY -a publish -x unsubscribe=0 -i agent.client.$ID -c false -v -v -m "$mesg" -x retainedFlag=1 2>&1 | tee -a log.agent.$ID.reply`
echo "$data"

data=`mqttsample_array -s $SERVER -n 1 -q 0 -t /CONFIRM -a publish -x unsubscribe=0 -i agent.client.$ID -c false -v -v -m "$mesg" -x retainedFlag=1 2>&1 | tee -a log.agent.$ID.confirm `
echo "$data"

mkdir logs.agent.id.$ID/logs.messageid.$replyid
mv log.agent.$ID.* logs.agent.id.$ID/logs.messageid.$replyid
rm -rf log.agent.$ID.*


echo ============================================================
echo ============================================================
echo ============================================================
echo "`date` : start usleep $(($S*2))"
#usleep $(($S*2))
usleep  1000
echo "`date` : done  usleep $(($S*2))"

done

fi
